<!--
 * @Author: huang liang miao 1127255342@qq.com
 * @Date: 2024-11-08 13:39:48
 * @LastEditors: huang liang miao 1127255342@qq.com
 * @LastEditTime: 2025-01-07 10:01:19
 * @FilePath: \dcy-webd:\webCode\dcyCode\scientific_research_manager_web\src\views\system\user\index.vue
 * @Description: 用户管理
-->

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { useRequest } from 'vue-hooks-plus'
import EditUser from "./components/EditUser.vue"
import formateDate from '@/utils/formateDate'
import { dictEnum } from '@/utils/constEnum';
import { identityCodeList } from  "@/utils/typeList"
import { userResult, result, importSuccess } from "@/utils/excelResult"
import { getAccountListPage, deleteAccountReq, updateStatusReq, resetPasswordReq, getDepartmentListReq, batchCreateListPage } from "@/api/system/user/index"
import { roleListReq } from "@/api/system/role/index"

const showSearch = ref(true)
const visible = ref(false)
const importVisible = ref(false)  // 导入用户
const templateUrl = '/userImport.xlsx' // 下载模板
const delVisible = ref(false)
const curItem = ref()
const userList = ref([])
const curId = ref('') // 当前行id
const total = ref(0)
const editType = ref(1) // 0-查看，1-新增，2-编辑

const { proxy } = getCurrentInstance()
const dict = proxy.useDict(dictEnum.firstDiscipline, dictEnum.jobTitle, dictEnum.jobLevel, dictEnum.jobType, dictEnum.qualification, dictEnum.degree)

const departmentList = ref() // 院/部
const roleList = ref() // 角色
const titleList = computed(() => {
  return dict[dictEnum.jobTitle]
}) // 职称
const subjectList = computed(() => {
   return dict[dictEnum.firstDiscipline]
}) // 学科
const positionLevelList = computed(() => {
   return dict[dictEnum.jobLevel]
}) // 岗位级别
const positionTypeList = computed(() => {
   return dict[dictEnum.jobType]
}) // 岗位类型
const educationNameList = computed(() => {
   return dict[dictEnum.qualification]
}) // 学历
const academicNameList = computed(() => {
   return dict[dictEnum.degree]
}) // 学位

const queryParams = ref<any>({
   page: 1,
   size: 20,
   codeOrName: '',
   codeOrPhone: '',
   inside: undefined,
   departmentId: undefined,
   titleId: undefined,
   positionLevelId: undefined,
   subjectId: undefined,
   organizationName: '',
   direction: '',
   roleId: undefined,
   identityCode: undefined,
   email: '',
   positionTypeId: undefined,
   sex: undefined,
   educationId: undefined,
   academicId: undefined,
   startTime: undefined,
   endTime: undefined,
})

// 搜索条件组件配置数据
const conditionComponents = computed<any>(() => [
   {
      type: 0,
      key: 'codeOrName',
      value: '',
      placeholder: '请输入姓名'
   },
   {
      type: 0,
      key: 'codeOrPhone',
      value: '',
      placeholder: '请输入工号或手机号'
   },
   {
      type: 1,
      key: 'inside',
      value: '单选框',
      placeholder: '是否校内用户',
      config: {
         options: [
         {title: '校内用户', value: true},
         {title: '校外用户', value: false},
         ]
      }
   },
   {
      type: 1,
      key: 'departmentId',
      value: '单选框',
      placeholder: '院校（部）',
      config: {
         options: departmentList.value
      }
   },
   {
      type: 1,
      key: 'titleId',
      value: '单选框',
      placeholder: '职称',
      config: {
         options: titleList.value
      }
   },
   {
      type: 1,
      key: 'positionLevelId',
      value: '单选框',
      placeholder: '岗位级别',
      config: {
         options: positionLevelList.value
      }
   },
   {
      type: 1,
      key: 'subjectId',
      value: '单选框',
      placeholder: '一级学科',
      config: {
         options: subjectList.value
      }
   },
   {
      type: 0,
      key: 'organizationName',
      value: '',
      placeholder: '请输入所属单位'
   },
   {
      type: 0,
      key: 'direction',
      value: '',
      placeholder: '请输入研究方向'
   },
   {
      type: 1,
      key: 'roleId',
      value: '单选框',
      placeholder: '角色',
      config: {
         options: roleList.value
      }
   },
   {
      type: 1,
      key: 'identityCode',
      value: '单选框',
      placeholder: '身份',
      config: {
         options: identityCodeList
      }
   },
   {
      type: 0,
      key: 'email',
      value: '',
      placeholder: '请输入邮箱'
   },
   {
      type: 1,
      key: 'positionTypeId',
      value: '单选框',
      placeholder: '岗位类型',
      config: {
         options: positionTypeList.value
      }
   },
   {
      type: 1,
      key: 'sex',
      value: '单选框',
      placeholder: '性别',
      config: {
         options: [
         {title: '男', value: 1},
         {title: '女', value: 2},
         ]
      }
   },
   {
      type: 1,
      key: 'educationId',
      value: '单选框',
      placeholder: '学历',
      config: {
         options: educationNameList.value
      }
   },
   {
      type: 1,
      key: 'academicId',
      value: '单选框',
      placeholder: '学位',
      config: {
         options: academicNameList.value
      }
   },
   {
      type: 2,
      key: 'calendar',
      value: '日历',
      width: "456px",
      startPlaceholder: '请选择出生日期开始时间',
      endPlaceholder: '请选择出生日期结束时间',
   },
])

// 表头
const columns = ref([
{
   title: '工号',
   minWidth: 40,
   dataIndex: 'code',
},
{
   title: '姓名',
   minWidth: 60,
   dataIndex: 'name',
},
{
   title: '手机号',
   minWidth: 60,
   dataIndex: 'phone',
},
{
   title: '邮箱',
   minWidth: 60,
   dataIndex: 'email',
},
{
   title: '角色',
   minWidth: 80,
   dataIndex: 'accountRoleList',
   formatter: (record) => {
      return record.accountRoleList?.map((v: any) => v.roleName).join(',') || '-'
   },
},
{
   title: '身份',
   minWidth: 80,
   dataIndex: 'identityCode',
   formatter: (record) => {
      return record.identityCode?.map((v: any) => identityCodeList.filter((n => n.value === v))[0].title).join(',') || '-'
   },
},
{
   title: '是否校内用户',
   minWidth: 60,
   dataIndex: 'inside',
   formatter: (record) => {
      return record.inside ? '是' : '否'
  },
},
{
   title: '学院(部)',
   minWidth: 80,
   dataIndex: 'departmentName',
},
{
   title: '性别',
   minWidth: 60,
   dataIndex: 'sex',
   formatter: (record) => {
      const sexList = {
         1: '男',
         2: '女'
      }
      return sexList[record.sex]
  },
},
{
   title: '出生日期',
   minWidth: 80,
   dataIndex: 'birthday',
   formatter: (record) => {
      return record.birthday && formateDate(record.birthday).format('YYYY/MM/DD')
   },
},
{
   title: '学历',
   minWidth: 60,
   dataIndex: 'educationName',
},
{
   title: '学位',
   minWidth: 60,
   dataIndex: 'academicName',
},
{
   title: '是否启用',
   minWidth: 60,
   dataIndex: 'status',
   slotName: 'status',
},
{
   title: '职称',
   minWidth: 70,
   dataIndex: 'title',
},
{
   title: '岗位类型',
   minWidth: 70,
   dataIndex: 'positionType',
},
{
   title: '岗位级别',
   minWidth: 70,
   dataIndex: 'positionLevel',
},
{
   title: '一级学科',
   minWidth: 70,
   dataIndex: 'subject',
},
{
   title: '所属单位',
   minWidth: 80,
   dataIndex: 'organizationName',
},
{
   title: '研究方向',
   minWidth: 80,
   dataIndex: 'direction',
},
{
   title: '操作',
   minWidth: 100,
   dataIndex: 'default',
   slotName: 'default',
}
])
// 获取学院/部列表
const { run: getDepartmentList } = useRequest(getDepartmentListReq, {
	manual: true,
	onSuccess: (res: any) => {
		res?.forEach((item) => {
			item.title = item.departmentName
			item.value = item.departmentId
      })
      departmentList.value = res
      conditionComponents.value[3].config.options = departmentList.value
	}
})
getDepartmentList()

// 查询用户列表
const { run: getAccountList, loading } = useRequest(getAccountListPage, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (data: any) => {
      userList.value = data.content || []
      total.value = data.totalElements
   },
})
onSearch()

// 查询角色列表
const { run: getRoleList } = useRequest(roleListReq, {
   // false 为自动执行
   manual: true,
   // 请求成功
   onSuccess: (data: any) => {
      data.forEach((item: any) =>{
         item.title = item.name
         item.value = item.id
      })
      conditionComponents.value[9].config.options = data
      roleList.value = data
   },
})
getRoleList({})

// 过滤查询
function onSearch() {
   // 身份需数组方式查询
   queryParams.value.identityCode = queryParams.value.identityCode ? [queryParams.value.identityCode] : undefined
   getAccountList(queryParams.value)
}

// 条件过滤
function formSearch(params){
   queryParams.value = {
      ...queryParams.value,
      ...params,
      calendar: undefined,
      startTime: params.calendar ? params.calendar[0] + ' 00:00:00' : undefined,
      endTime: params.calendar ? params.calendar[1] + ' 23:59:59' : undefined,
   }
   onSearch()
}

// 用户禁用启用
const { run: updateStatus, loading: switchLoading } = useRequest(updateStatusReq, {
  manual: true,
  onSuccess: () => {
      let text = curItem.value.status ? "启用" : "禁用"
      ElMessage({
         message: `${text}成功`,
         type: 'success',
      })
      onSearch()
  }
})
function statusChange(item) {
   curItem.value = item
   if(item.accountRoleList?.filter((v: any) => v.admin).length === 0 )
      updateStatus({status: item.status, id: item.id})
}

// 删除
const { run: deleteDict, loading: delLoading } = useRequest(deleteAccountReq, {
  manual: true,
  onSuccess: () => {
    delVisible.value = false
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
    onSearch()
  }
})
const handleDelete = (dictId) => {
  curId.value = dictId
  delVisible.value = true
}
// 重置当前用户密码
const { run: resetPassword, loading: reserLoading } = useRequest(resetPasswordReq, {
  manual: true,
  onSuccess: () => {
      delVisible.value = false
      ElMessage({
         message: '密码已重置',
         type: 'success',
      })
      onSearch()
  }
})
function resetUserPwd(cid){
   ElMessageBox.confirm(
      '是否重置当前用户密码?',
      "",
      {
         type: 'warning',
         closeOnClickModal: false,
         'show-close': false,
         loading: reserLoading.value,
      }
   )
   .then(function () {
      return resetPassword({id: cid})
   })
}

function changeUser(i: number, item?: any){
   editType.value = i
   curItem.value = item || null
   visible.value = true
}
function close(v: boolean){
   if(v){
      onSearch()
   }
   visible.value = false
   importVisible.value = false
}

// 用户导入
const { run: userBatchCreateList, loading: userLoading} = useRequest(batchCreateListPage, {
  // false 为自动执行
  manual: true,
  // 请求成功
  onSuccess: (res: any) => {
    result(res)
    if(importSuccess.value){
      importVisible.value = false
      onSearch()
    }
  },
})
function importSubmit(item: any){
   userBatchCreateList(userResult(item))
}

</script>

<template>
   <div class="user-container">
      <div v-show="showSearch" class="form">         
         <SearchBar :components="conditionComponents" :hide-right-area="false" @search="formSearch" />
      </div>
      <div class="user-list">
         <TableForm
            :auto-height='true'
            :data="userList"
            :columns="columns"
            :tableLoading="loading"
            :total-count="total"
            :hideRightFirstBtn="true"
            :hideRightSecondBtn="true"
            :hideRightForthBtn="true"
            v-model:showSearch="showSearch"
            :showToolBar="true"
            @refresh="formSearch"
         >
            <template #leftMenu>
               <el-button type="primary" @click="changeUser(1)">新增用户</el-button>
               <el-button @click="importVisible = true">批量导入</el-button>
            </template>
            <template #status="{record}">
               <el-switch
                  v-model="record.status"
                  :disabled="record.accountRoleList?.filter((v: any) => v.admin).length > 0"
                  :loading="switchLoading"
                  @click="statusChange(record)"
               ></el-switch>
            </template>
            <template #default="{record}">
               <!-- <el-button link type="primary" @click="changeUser(0, record)">查看</el-button> -->
               <el-button link type="primary" @click="changeUser(2,record)">编辑</el-button>
               <el-button link type="primary" @click="resetUserPwd(record.id)">重置密码</el-button>
               <el-button v-if="record.accountRoleList?.filter((v: any) => v.admin).length === 0 && !record.status" link type="danger" @click="handleDelete(record.id)">删除</el-button>
            </template>
         </TableForm>
      </div>

      <!-- 新增编辑/查看 -->
      <EditUser v-if="visible" :visible="visible" :editType="editType" :curItem="curItem" :titleList="titleList" :roleList="roleList" :departmentList="departmentList" :subjectList="subjectList" :positionTypeList="positionTypeList" :positionLevelList="positionLevelList" :educationNameList="educationNameList" :academicNameList="academicNameList" @close="close" />
      
      <!-- 删除提示 -->
      <DelConfirmModal v-if="delVisible" :visible="delVisible" :loading="delLoading" text="删除后无法恢复，是否确认删除？" @cancel="delVisible = false" @ok="deleteDict({id: curId})" />

      <!-- 导入用户 -->
      <BulkImport v-if="importVisible" :visible="importVisible" fileName="导入用户" :url="templateUrl" :loading="userLoading" @cancel="close" @submit="importSubmit" />
   </div>
</template>

<style lang="scss" scoped>
.user-container{
   .form{
      @apply: p-[20px] bg-white rounded-[8px] mb-[16px];
      &:has(.search-bar-expand) {
         @apply: pb-[8px]
      }
   }
   .user-list{
      @apply: px-[20px] pb-[20px] pt-[4px] bg-white rounded-[8px];
   }
}
</style>